package com.imooc.town.service.impl;

import com.imooc.town.dataobject.ProductInfo;
import com.imooc.town.dto.CartDTO;
import com.imooc.town.enums.ProductStatusEnum;
import com.imooc.town.enums.ResultEnum;
import com.imooc.town.exception.SellException;
import com.imooc.town.reponsitory.ProductInfoReponsitory;
import com.imooc.town.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 10077 on 2018/3/21.
 * desc:
 */

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoReponsitory reponsitory;

    @Override
    public ProductInfo getOne(String productId) {
        return reponsitory.getOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return reponsitory.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return reponsitory.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return reponsitory.save(productInfo);
    }

    @Override
    public void increateStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = reponsitory.getOne ( cartDTO.getProductId () );
            if (productInfo == null){
                throw new SellException ( ResultEnum.PRODUCT_NOT_EXIST );
            }
            productInfo.setProductStock ( cartDTO.getProductQuantity () + productInfo.getProductStock ());
            reponsitory.save ( productInfo );
        }
    }

    @Override
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = reponsitory.getOne ( cartDTO.getProductId () );
            productInfo.setProductStock ( productInfo.getProductStock ()-cartDTO.getProductQuantity ());
            reponsitory.save ( productInfo );
        }
    }
}
